﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using ActionPluginAPI;
using System.IO;
using System.Diagnostics;
using System.Windows.Forms;
using iMapa.Helper;

namespace RunCommandActionPlugin
{
    public class RunCommandActionPlugin : IActionPlugin
    {

        public AbstractActionConfigPanel GetConfigPanel(IActionParameters parameters)
        {
            return new RunCommandConfigPanel(parameters);
        }

        public IActionParameters GetNewParametersInstance(string rootPath)
        {
            return new RunCommandActionParameters();
        }

        public IActionParameters LoadFromFile(string filename)
        {
            RunCommandActionParameters parameter = ObjectXMLSerializer<RunCommandActionParameters>.Load(filename);
            parameter.SetID(new FileInfo(filename).Name);
            return parameter;
        }

        public void Execute(IActionParameters parameters)
        {
            if(parameters!=null && parameters is RunCommandActionParameters){
                RunCommandActionParameters p= (RunCommandActionParameters)parameters;
                startProcess(p.Directory,p.Command,p.Arguments);
            }
        }

        public string GetName()
        {
            return "Execute external command";
        }

        private void startProcess(string Path, string fileName,string args)
        {
            try
            {
                Process install = new Process();
                install.StartInfo.WorkingDirectory = Path;
                install.StartInfo.FileName = fileName;
                install.StartInfo.Arguments = args;
                install.Start();
            }
            catch (Exception e)
            {
                MessageBox.Show(e.Message, "error", MessageBoxButtons.OK, MessageBoxIcon.Error);

            }
        }

    }


}
